package com.jerry.template.module.mainpage.msg.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.jerry.template.base.MyDBHelper;
import com.jerry.template.module.mainpage.msg.entity.User;

/**
 * Created by czy on 2016/5/16.
 */
public class DBAccess {
    private static DBAccess dba;
    private static MyDBHelper helper;

    public static DBAccess getInstance(Context context) {
        if (dba == null) {
            synchronized (DBAccess.class) {
                if (dba == null) {
                    dba = new DBAccess(context);
                }
            }
        }
        return dba;
    }

    public DBAccess(Context context) {
        helper = new MyDBHelper(context);
    }

    public void add(User user) {
        //获取一个数据库对象
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", user.getName());
        values.put("password", user.getPassword());
        values.put("sex", user.getSex());

        db.insert("user", null, values);

        Log.d("添加成功", "添加成功");

        db.close();
    }

    public int login(String name, String password) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from User where name=?", new String[]{name});

        if (cursor.getCount() > 0) {
            Cursor pwdcursor = db.rawQuery("select * from User where password=? and name=?", new String[]{password, name});
            if (pwdcursor.getCount() > 0) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return 0;
        }
    }
}
